﻿/// <reference path="/Scripts/MicrosoftAjax/MicrosoftAjax.debug.js"/>
/// <reference path="/WebUI/core.debug.js"/>
/// <reference path="/WebUI/DataView/script.debug.js" />

Doo.UserControlBase = function (element) {
    Doo.UserControlBase.initializeBase(this, [element]);
}

Doo.UserControlBase.HtmlCache = {};

Doo.UserControlBase.prototype = {
    initialize: function () {
        Doo.UserControlBase.callBaseMethod(this, 'initialize');
        if (this.autoShow) {
            var _t = this;
            setTimeout(function () { _t.show(); }, 0);

        }
        else {
            this.domReady(this.get_element());
        }
    },
    path: '',
    htmlfile: '',
    appendversion: 0, //版本号，如大于0则将附加版本号数据
    htmlcontent: 0,
    usePath: true,
    useHtmlFile: true,
    useTemplateBinder: true, //是否使用模版引擎
    autoShow: true,
    getHtml: function (file, callback) {
        ///<summary>远程加载模版，并在加载完成时调用callback</summary>
        /// <param name="callback" type="Function">callback(html)</param>
        var version = this.appendversion;
        if (file.charAt(0) != '/' && this.usePath) {
            file = this.path + file;
            if (version == 0) {
                version = Doo.ControlLoader.getVersionByPath(file) || 0;
            }
        }
        if (version != 0) {
            file += (file.indexOf('?') < 0 ? '?' : '&') + 'v=' + version;
        }
        var callbacks;
        if (file in Doo.UserControlBase.HtmlCache) {
            callbacks = Doo.UserControlBase.HtmlCache[file];
            if (String.isInstanceOfType(callbacks)) {//如果是string，表示是已经加载的内容。如果不是，表示是数组
                this.setHtml(callbacks);
                return;
            }
            callbacks.push(callback);
        }
        else {
            callbacks = [callback];
            Doo.UserControlBase.HtmlCache[file] = callbacks;
            var request = new Sys.Net.WebRequest();
            request.set_url(file);
            request.set_userContext(file);
            request.add_completed(this.getHtml_ok);
            request.invoke();
        }
    },
    getHtml_ok: function (response) {
        /// <param name="result" type="Sys.Net.WebRequestExecutor">根元素</param>
        var file = response.get_webRequest().get_userContext();
        var html = response.get_responseData();
        var callbacks = Doo.UserControlBase.HtmlCache[file];
        Doo.UserControlBase.HtmlCache[file] = html;
        for (var i = 0; i < callbacks.length; i++) {
            callbacks[i](html);
        }
    },
    compiledHtmlTpl: null,
    createBindData: function () {
        ///<summary>在派生类中重载用于获取用来绑定模版的数据</summary>
        return 0;
    },
    setHtml: function (html) {
        var delegate = Function.createDelegate(this,
                function (frag) {
                    var element = this.get_element();
                    element.innerHTML = "";
                    element.appendChild(frag);
                    this.domReady(element);
                    this.onChildsReady();
                });
        if (this.useTemplateBinder) {
            if (this.compiledHtmlTpl == null) { this.compiledHtmlTpl = Doo.TemplateBinder.Compiler(html); };
            Doo.TemplateBinder.BindEx(this, { root: this.compiledHtmlTpl }, this.createBindData(), delegate);
        }
        else {
            Doo.Utils.Dom.createElement(html, delegate);
        }
    },
    dispose: function () {
        //Add custom dispose actions here
        Doo.UserControlBase.callBaseMethod(this, 'dispose');
    },
    _isDomReady: false,
    domReady: function (root) {
        ///<summary>在Dom准备好时触发</summary>
        /// <param name="root" DomElement="true">根元素</param>
        this._isDomReady = true;
        this.ondomready(this, root); //调用系统
        this.onDomReady(root); //调用派生类
        this.onready();
        //为下属控件调用load方法
        if (this.childs && this.childs.length > 0) {
            Array.forEach(this.childs, function (c) { if (c.load) c.load(); });
        }
    },
    onDomReady: function (root) {
        ///<summary>在派生类重写时，在创建的树上实例自己的控件</summary>
    },
    show: function () {
        ///<summary>展示控件</summary>
        if (!this._isDomReady) {
            if (!this.useHtmlFile) {
                if (!this.htmlcontent) {
                    this.domReady(this.get_element());
                }
                else {
                    this.setHtml(this.htmlcontent);
                }
                return;
            }

            if (!this.htmlfile) {
                var _t = this;
                setTimeout(function () { _t.domReady(_t._element); _t.onChildsReady(); }, 0);
                return 0;
            }

            var _this = this;
            var v = this.get_asyncver();
            this.getHtml(this.htmlfile, function (html) {
                if (!_this.checkAsync(v)) return;
                _this.setHtml(html);
            });
        }
    }
}
Doo.Scripts.SetEvents(Doo.UserControlBase.prototype, { ready: 0, "domready": 0 }); //domready小写
Doo.UserControlBase.registerClass('Doo.UserControlBase', Doo.ControlBase);

Doo.Page = function (element) {
    Doo.Page.initializeBase(this, [element]);
}

Doo.Page.prototype = {
    initialize: function () {
        this.useHtmlFile = false;
        this.autoShow = false;

        Doo.Page.callBaseMethod(this, 'initialize');

    },
    createBindData: function () {
        ///<summary>在派生类中重载用于获取用来绑定模版的数据</summary>
        return window;
    },
    callback: null,
    onDomReady: function (root) {
        ///<summary>在派生类重写时，在创建的树上实例自己的控件</summary>
        if (this.callback) { this.callback(); }
    },
    onChildsReady: function () {
        if (this.childs && this.childs.length > 0) {
            Array.forEach(this.childs, function (c) { if (c.load) c.load(); });
        }
        this.load();
    }
}
Doo.Page.registerClass('Doo.Page', Doo.UserControlBase);
Doo.PageType = Doo.Page;
Doo.PageRoot = null;
Doo.PageInit = Function.emptyFunction;
Doo.PageAreas = null;
//Page
//doo_page
Doo$PageCreate = function (rootelement, callback) {
    //创建一个Doo页面，必须引用DataView.script.debug.js
    var source = rootelement.innerHTML;
    $Page = $create(Doo.PageType, { callback: callback, htmlcontent: source }, null, null, rootelement);
}
Sys.Application.add_init(function () {
    if (!Doo.PageRoot) Doo.PageRoot = document.body;
    Doo$PageCreate(Doo.PageRoot, Doo.PageInit);
    $Page.beginCreateChilds();
    if (Doo.PageAreas && Doo.PageAreas.length) {
        var pa = Doo.PageAreas;
        for (var i = 0; i < pa.length; i += 2) {
            var parent = pa[i + 1] ? window[pa[i + 1]] : $Page;
            Doo$AreaCreate(pa[i], parent);
        }
    }
    $Page.endCreateChilds();
});

Doo$AreaCreate = function (rootelementorid, parent) {
    ///<summary>在一个区域内创建控件集，并将创建的控件添加到上级</summary>
    ///<param name="parent" type="Doo.ControlBase"></param>
    if (typeof (rootelementorid) == 'string') rootelementorid = $get(rootelementorid);
    if (!rootelementorid) return; 
    var source = rootelementorid.innerHTML;
    var cmtpl = { root: Doo.TemplateBinder.Compiler(source) };
    parent.beginCreateChilds();
    Doo.TemplateBinder.BindEx(parent, cmtpl, 0, function (frag) {
        rootelementorid.innerHTML = "";
        rootelementorid.appendChild(frag);
        parent.endCreateChilds();
    });


    //Doo.Utils.Dom.setHtmlAsync(rootelementorid, html, function () { parent.ondomready(); });
}

